#!/bin/bash

trap "exit 1" INT TERM

TREMX_VERSION="001"

PLATFORM=`uname | sed -e s/_.*// | tr '[:upper:]' '[:lower:]' | sed -e 's/\//_/g'`
ARCH=`uname -m | sed -e s/i.86/x86/`

ROOT_DIRECTORY=`pwd`
DIST_DIRECTORY="${HOME}/.tremulous"
RES_DIRECTORY="$ROOT_DIRECTORY/misc/resources"
BUILD_DIRECTORY="$ROOT_DIRECTORY/build/release-$PLATFORM-$ARCH"

if [ ! -d $DIST_DIRECTORY/tremx ]; then
	echo "Creating directory: \"$DIST_DIRECTORY/tremx\""
	mkdir -p $DIST_DIRECTORY/tremx
fi

if [ ! -d $RES_DIRECTORY/vms-tremx/vm ]; then
	echo "Creating directory: \"$RES_DIRECTORY/vms-tremx/vm\""
	mkdir -p $RES_DIRECTORY/vms-tremx/vm
fi

echo

cd $ROOT_DIRECTORY && BUILD_GAME_QVM=1 make

if [ ! $? = 0 ]; then
	exit $?
else
	cp $BUILD_DIRECTORY/base/vm/*.qvm $RES_DIRECTORY/vms-tremx/vm
fi

echo

echo "Building \"tremx_data_$TREMX_VERSION.pk3\""
cd $RES_DIRECTORY/tremx-data
zip -9rq tremx_data_$TREMX_VERSION.pk3 .
echo "Building \"tremx_vms_$TREMX_VERSION.pk3\""
cd $RES_DIRECTORY/vms-tremx
zip -9rq tremx_vms_$TREMX_VERSION.pk3 .

echo

echo "Copying \"tremx_data_$TREMX_VERSION.pk3\" to \"$DIST_DIRECTORY/tremx\""
cp $RES_DIRECTORY/tremx-data/tremx_data_$TREMX_VERSION.pk3 $DIST_DIRECTORY/tremx
echo "Copying \"tremx_vms_$TREMX_VERSION.pk3\" to \"$DIST_DIRECTORY/tremx\""
cp $RES_DIRECTORY/vms-tremx/tremx_vms_$TREMX_VERSION.pk3 $DIST_DIRECTORY/tremx
echo "Copying \"tremulous.x86\" to \"$DIST_DIRECTORY\""
cp $BUILD_DIRECTORY/tremulous.x86 $DIST_DIRECTORY
echo "Copying \"tremded.x86\" to \"$DIST_DIRECTORY\""
cp $BUILD_DIRECTORY/tremded.x86 $DIST_DIRECTORY
